package com.itrip.utils;

import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisAPI {

    private JedisPool jedisPool;

    public JedisPool getJedisPool(){
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool){
        this.jedisPool = jedisPool;
    }

    public String get(String key){
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            return jedis.get(key);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
        return null;
    }

    public boolean set(String key,String value){
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.set(key,value);
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
        return false;
    }

    public boolean setex(String key,int seconds,String value){
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.setex(key, seconds, value);
            return true;
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
        return false;
    }

    public Long ttl(String key){
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            return jedis.ttl(key);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
        return -1l;
    }

    public void del(String key){
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.del(key);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            returnResource(jedisPool,jedis);
        }
    }

    public static void returnResource(JedisPool pool,Jedis jedis){
        if(jedis != null){
            pool.returnResource(jedis);
        }
    }

}
